package testcode;

import com.example.start.Address;
import com.example.start.Contacts;
import com.example.start.PeopleInfo;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

public class TestRead {
    public static void main(String[] args) throws IOException {
        // 从磁盘⽂件⾥读取，并反序列化为 Message 实例
        Contacts contacts = Contacts.parseFrom(
                new FileInputStream("src/main/java/com/example/start/contacts.bin"));
        // 打印
        printContacts(contacts);
        //System.out.println(contacts.toString());
    }

    private static void printContacts(Contacts contacts) throws InvalidProtocolBufferException {
        for (int i = 0; i < contacts.getContactsCount(); i++) {
            System.out.println("--------------联系⼈" + (i + 1) + "-----------");
            PeopleInfo peopleInfo = contacts.getContacts(i);
            System.out.println("姓名: " + peopleInfo.getName());
            System.out.println("年龄: " + peopleInfo.getAge());
            int j = 1;
            for (PeopleInfo.Phone phone : peopleInfo.getPhoneList()) {
                System.out.println("电话" + (j++) + ": " + phone.getNumber() + " (" + phone.getType().name() + ")");
            }

            if (peopleInfo.hasData() && peopleInfo.getData().is(Address.class)) {
                Address address = peopleInfo.getData().unpack(Address.class);
                if (!address.getHomeAddress().isEmpty()) {
                    System.out.println("家庭地址：" + address.getHomeAddress());
                }
                if (!address.getUnitAddress().isEmpty()) {
                    System.out.println("单位地址：" + address.getUnitAddress());
                }
            }

            switch (peopleInfo.getOtherContactCase()) {
                case QQ:
                    System.out.println("qq号：" + peopleInfo.getQq());
                    break;
                case WECHAT:
                    System.out.println("微信号：" + peopleInfo.getWechat());
                    break;
                case OTHERCONTACT_NOT_SET:
                    break;
            }

            for (Map.Entry<String, String> entry : peopleInfo.getRemarkMap().entrySet()) {
                System.out.println(" " + entry.getKey() + " : " + entry.getValue());
            }
        }
    }
}
